package com.zuilapsa.jmc.exporters;

import org.dom4j.*;

import com.zuilapsa.jmc.*;

/**
 * Producer of all exporters. Class tries to reuse existing exporters.
 * 
 * @author beda
 * 
 */
public class ExporterProducer {
	protected static ExporterProducer producer = null;

	private ExporterProducer() {

	}

	public static ExporterInterface getExporter(Element element) throws JmcException {
		return getInstance().getExporterInstance(element);
	}

	protected ExporterInterface getExporterInstance(Element element) throws JmcException {
		ExporterInterface classInstance = null;
		try {
			String exporterName = element.attributeValue("name");
			String className = element.attributeValue("class");
			String scriptName = element.attributeValue("script");
			if (exporterName == null) {
				throw new JmcException("Lack of name attribute in exporter definition");
			}
			if (scriptName != null && className != null) {
				throw new JmcException("Abigous exporter definition: "+element.asXML());
			}
			if (className != null) { 
				Class classClass = Class.forName(className);
				classInstance = (ExporterInterface)classClass.newInstance();
			}
			if (scriptName != null) {
				classInstance = new ExporterBean(exporterName, scriptName);
			}
		} catch (ClassNotFoundException e) {
			System.err.println("The exporter was not found");
			throw new JmcException("The exporter was not found", e);
		} catch (Exception e) {
			System.err.println("The exporter happend to be wrong");
			throw new JmcException("The exporter happend to be wrong", e);
		}
		return classInstance;
	}

	public static ExporterProducer getInstance() {
		if (producer == null) {
			producer = new ExporterProducer();
		}
		return producer;
	}
}
